#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "methodget.h"

#define PI 3.14159265

void PrintHTTPResponseHeader(void)
{
	printf("Content-Type: text/html;charset=utf-8\n\n");
}

void PrintHTMLStyles(void)
{
	printf("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/style.css\" />\n");
}

void PrintHTMLHead(void)
{
	printf("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n\"http://www.w3.org/TR/html4/loose.dtd\">\n");
	printf("<html>\n");
	printf("<head>\n");
	printf("<title>Sin table</title>\n");
	PrintHTMLStyles();
	printf("</head>\n");
	printf("<body>\n");
}

void PrintSinTable(int degreeInterval, int minuteInterval)
{
	int i, j, odd = 1, numResult = 0;
	double result = 0;

	printf("<table>\n");
	for (i = 0; i <= 360; i += degreeInterval)
	{        
		(odd && (i > 0)) ? printf("<tr class=\"odd\">\n") : printf("<tr>\n");
		odd = 1 - odd;
		(i == 0) ? printf("<td></td>\n") : printf("<td class=\"name\"><strong>%d</strong></td>", i);
		for (j = 0; j <= 60; j += minuteInterval)
		{
			result = sin((j / 60.0 + i) * (PI / 180.0));
			(i == 0) ? printf("<td class=\"name\"><strong>%d\'</strong></td>", j) : printf("<td>%f</td>", result);
		}
		printf("\n</tr>\n");
	}
	printf("</table>\n");
}

void PrintHTMLEnd(void)
{
	printf("</body>\n");
	printf("</html>\n");
}

int StringToInt(const char * str)
{
	if (!str)
	{
		return 0;
	}
	char * pLastChar = NULL;
	int param = strtol(str, &pLastChar, 10);
	return param;
}

void SearchIntervals(int * degreeInterval, int * minuteInterval, const char * const data)
{
	int err = 0;
	char value[255];
	if (GetValue("degree", data, &value[0], &err))
	{
		if (((*degreeInterval = StringToInt(&value[0])) <= 0) || (*degreeInterval > 360))
		{
			*degreeInterval = 10;
		}
	}
	if (GetValue("minute", data, &value[0], &err))
	{
		if (((*minuteInterval = StringToInt(&value[0])) <= 0) || (*minuteInterval > 60))
		{
			*minuteInterval = 6;
		}
	}
}

void GetIntervals(int * degreeInterval, int * minuteInterval)
{
	char * data = getenv("QUERY_STRING");
	if (*data != '\0')
	{
		char newData[255];
		AddSpecialSymbols(data, newData, '?', 0);
		SearchIntervals(degreeInterval, minuteInterval, newData);
	}
}

void main(void)
{
	PrintHTTPResponseHeader();

	int degreeInterval = 10, minuteInterval = 6;
	
	PrintHTMLHead();
	GetIntervals(&degreeInterval, &minuteInterval);
	PrintSinTable(degreeInterval, minuteInterval);
	PrintHTMLEnd();
}